package com.heima.wemedia.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.file.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import com.heima.wemedia.dao.WmMaterialDao;
import com.heima.wemedia.dao.WmNewsMaterialDao;
import com.heima.wemedia.service.WmMaterialService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 自媒体素材表(WmMaterial)表服务实现类
 *
 * @author makejava
 * @since 2022-04-10 16:44:10
 */
@Service("wmMaterialService")
public class WmMaterialServiceImpl implements WmMaterialService {

    @Resource
    private WmMaterialDao wmMaterialDao;

    @Resource
    private MinIOTemplate minIOTemplate;

    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;


    /**
     * 素材文件上传
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {

        //1.校验参数
        if (file == null || file.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //获取原始文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //生成新的文件名
        String name = UUID.randomUUID().toString().replace("-", "") + suffix;

        //上传文件到minio
        String url = null;
        try {
            url = minIOTemplate.uploadImgFile("", name, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //封装数据保存到素材表，并返回给前端
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getId());
        wmMaterial.setUrl(url);
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(0);
        wmMaterial.setCreateTime(new Date());
        wmMaterial.setUpdateTime(new Date());
        wmMaterialDao.insert(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        //2.1封装查询条件
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getId());    //用户id
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wmMaterial.setIsCollection(dto.getIsCollection());  //是否查询收藏
        }

        //2.2开启分页查询
        PageHelper.startPage(dto.getPage(), dto.getSize());
        Page<WmMaterial> page = wmMaterialDao.queryAll(wmMaterial);
        //封装数据返回
        ResponseResult result = new PageResponseResult(page.getPages(), page.getPageSize(), (int) page.getTotal());
        result.setData(page.getResult());
        return result;
    }

    @Override
    public ResponseResult deleteBy(Long id) {
        //校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询数据库获取文件路径
        WmMaterial wmMaterial = wmMaterialDao.queryById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = wmMaterial.getUrl();
        //TODO 完善删除素材前是否被文章引用，如有引用则不能删除
        //通过素材ID查询文章素材关联表获取关联表id集合，
        List<Long> ids = wmNewsMaterialDao.queryByMaterialId(id);
        if (Collections.isEmpty(ids)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该素材已被文章引用，无法删除");
        }
        minIOTemplate.delete(url);
        wmMaterialDao.deleteById(id);
        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult collect(Long id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置收藏值为1
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(1);
        wmMaterialDao.update(wmMaterial);
        return ResponseResult.okResult("收藏成功");
    }

    @Override
    public ResponseResult cancelCollect(Long id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置收藏值为0
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(0);
        wmMaterialDao.update(wmMaterial);
        return ResponseResult.okResult("取消收藏成功");
    }
}
